package com.ibeeking.found.msg.rest.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.ibeeking.found.common.enums.DefaultEnum;
import com.ibeeking.found.common.enums.PublishStatusEnum;
import com.ibeeking.found.common.utils.UserUtils;
import com.ibeeking.found.msg.rest.service.IEmailConfigService;
import com.ibeeking.found.msg.service.common.bo.EmailConfigBO;
import com.ibeeking.found.msg.service.common.bo.EmailConfigSslBO;
import com.ibeeking.found.msg.service.common.dos.EmailConfigDO;
import com.ibeeking.found.msg.service.common.param.EmailConfigParam;
import com.ibeeking.found.msg.service.common.param.EmailConfigSslParam;
import com.ibeeking.found.msg.service.common.vo.EmailConfigSslVO;
import com.ibeeking.found.msg.service.common.vo.EmailConfigVO;
import com.ibeeking.found.msg.service.mapper.EmailConfigMapper;
import com.ibeeking.nematos.core.utils.SpringBeanUtil;
import com.ibeeking.nematos.exception.BusinessException;
import com.ibeeking.nematos.utils.bean.BeanUtil;
import com.ibeeking.nematos.utils.cryptor.PasswordCryptor;
import com.ibeeking.nematos.utils.cryptor.SimplePasswordCryptor;
import com.ibeeking.nematos.utils.data.Collections3;
import com.ibeeking.nematos.utils.json.JsonUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

/**
 * EmailConfigServiceImpl
 * description 邮件服务器配置服务
 * @Author ibeeking
 * @Date 2020-12-09 10:54
 */
@Service
public class EmailConfigServiceImpl  extends ServiceImpl<EmailConfigMapper, EmailConfigDO> implements IEmailConfigService {


    @Resource
    private EmailConfigMapper emailConfigMapper;

    /**
     * 邮件服务器列表
     *
     * @param
     * @return
     */
    @Override
    public List<EmailConfigVO> listEmailConfig() {
        List<EmailConfigDO> emailConfigDOs = emailConfigMapper.selectList(new LambdaQueryWrapper<EmailConfigDO>());
        List<EmailConfigVO> emailConfigVOs = JsonUtils.jsonToList(emailConfigDOs, EmailConfigVO.class);
        List<EmailConfigVO> emailConfigResultVOS = new ArrayList<>();
        if(Collections3.isNotEmpty(emailConfigVOs)){
            emailConfigResultVOS = emailConfigVOs.stream().map(d-> {
                EmailConfigVO emailConfigVO = BeanUtil.convertBean(d, EmailConfigVO.class);
                if(StringUtils.isNotEmpty(emailConfigVO.getOtherInfo())) {
                    EmailConfigSslVO emailConfigSslVO = JsonUtils.fromJson(d.getOtherInfo(), EmailConfigSslVO.class);
                    if(emailConfigSslVO != null){
                        emailConfigVO.setEmailConfigSsl(emailConfigSslVO);
                    }
                }
                emailConfigVO.setHaveDefaultName(DefaultEnum.getEnum(d.getHaveDefault()).getDesc());
                emailConfigVO.setPublishStatusName(PublishStatusEnum.getName(d.getPublishStatus()));
                return emailConfigVO;
            }).collect(Collectors.toList());
        }
        return emailConfigResultVOS;
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public Boolean modifyEmailConfig(EmailConfigParam emailConfigParam) {
        Long userId = UserUtils.getUserId();

        EmailConfigSslParam  emailConfigSslParam = emailConfigParam.getEmailConfigSsl();
        if(StringUtils.isNotEmpty(emailConfigParam.getSenderEmailPassword())) {
            PasswordCryptor passwordCryptor = new SimplePasswordCryptor();
            emailConfigParam.setSenderEmailPassword(passwordCryptor.encrypt(emailConfigParam.getSenderEmailPassword()));
        }

        EmailConfigDO emailConfigDO = BeanUtil.convertBean(emailConfigParam, EmailConfigDO.class);
        if(emailConfigSslParam != null ){
            emailConfigDO.setOtherInfo(JsonUtils.toJsonStr(emailConfigSslParam));
        }
        emailConfigDO.setModifyBy(userId);
        emailConfigDO.setModifyTime(LocalDateTime.now());
        return emailConfigMapper.updateById(emailConfigDO) > 0;
    }

    @Override
    public EmailConfigVO viewDefaultEmailConfig() {
        EmailConfigDO emailConfigDO = emailConfigMapper.selectOne(new LambdaQueryWrapper<EmailConfigDO>()
                                            .eq(EmailConfigDO::getHaveDefault,new Integer(1)));
        if(emailConfigDO == null) {
            throw new BusinessException("无法获取缺省的邮件服务配置");
        }
        EmailConfigVO emailConfigVO = BeanUtil.convertBean(emailConfigDO, EmailConfigVO.class);
        if(StringUtils.isNotEmpty(emailConfigVO.getOtherInfo())) {
            EmailConfigSslVO emailConfigSslVO = JsonUtils.fromJson(emailConfigVO.getOtherInfo(), EmailConfigSslVO.class);
            if(emailConfigSslVO != null){
                emailConfigVO.setEmailConfigSsl(emailConfigSslVO);
            }
        }
        emailConfigVO.setHaveDefaultName(DefaultEnum.getEnum(emailConfigVO.getHaveDefault()).getDesc());
        emailConfigVO.setPublishStatusName(PublishStatusEnum.getName(emailConfigVO.getPublishStatus()));

        if(StringUtils.isNotEmpty(emailConfigDO.getSenderEmailPassword())) {
            PasswordCryptor passwordCryptor = new SimplePasswordCryptor();
            emailConfigVO.setSenderEmailPassword(passwordCryptor.decrypt(emailConfigDO.getSenderEmailPassword()));
        }
        return emailConfigVO;
    }

    @Override
    public EmailConfigVO viewEmailConfig(Long id) {
        EmailConfigDO emailConfigDO = emailConfigMapper.selectById(id);
        if(emailConfigDO == null) {
            throw new BusinessException("无法获取缺省的邮件服务配置");
        }
        EmailConfigVO emailConfigVO = BeanUtil.convertBean(emailConfigDO, EmailConfigVO.class);
        if(StringUtils.isNotEmpty(emailConfigVO.getOtherInfo())) {
            EmailConfigSslVO emailConfigSslVO = JsonUtils.fromJson(emailConfigVO.getOtherInfo(), EmailConfigSslVO.class);
            if(emailConfigSslVO != null){
                emailConfigVO.setEmailConfigSsl(emailConfigSslVO);
            }
        }
        emailConfigVO.setHaveDefaultName(DefaultEnum.getEnum(emailConfigVO.getHaveDefault()).getDesc());
        emailConfigVO.setPublishStatusName(PublishStatusEnum.getName(emailConfigVO.getPublishStatus()));
        if(StringUtils.isNotEmpty(emailConfigDO.getSenderEmailPassword())) {
            SimplePasswordCryptor passwordCryptor = new SimplePasswordCryptor();
            emailConfigVO.setSenderEmailPassword(passwordCryptor.decrypt(emailConfigDO.getSenderEmailPassword()));
        }
        return emailConfigVO;
    }

    @Override
    public EmailConfigBO queryEmailConfigById(Long id) {
        EmailConfigDO emailConfigDO = emailConfigMapper.selectById(id);
        EmailConfigBO emailConfigBO = BeanUtil.convertBean(emailConfigDO, EmailConfigBO.class);
        if(StringUtils.isNotEmpty(emailConfigDO.getSenderEmailPassword())) {
            SimplePasswordCryptor passwordCryptor = new SimplePasswordCryptor();
            emailConfigBO.setSenderEmailPassword(passwordCryptor.decrypt(emailConfigDO.getSenderEmailPassword()));
        }
        if(StringUtils.isNotEmpty(emailConfigBO.getOtherInfo())) {
            EmailConfigSslBO emailConfigSslBO = JsonUtils.fromJson(emailConfigBO.getOtherInfo(), EmailConfigSslBO.class);
            if(emailConfigSslBO != null){
                emailConfigBO.setEmailConfigSsl(emailConfigSslBO);
            }
        }
        return emailConfigBO;
    }

    @Override
    public Boolean changePublishStatus(Long id, Integer status) {
        Long userId = UserUtils.getUserId();
        EmailConfigDO emailConfigDO =  emailConfigMapper.selectById(id);
        if(emailConfigDO == null){
            throw new BusinessException("记录不存在");
        }
        emailConfigDO.setPublishStatus(status);
        emailConfigDO.setModifyBy(userId);
        emailConfigDO.setModifyTime(LocalDateTime.now());
        return emailConfigMapper.updateById(emailConfigDO) > 0;
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public Boolean changeDefaultStatus(Long id, Integer status) {
        Long userId = UserUtils.getUserId();
        if(status == DefaultEnum.YES.getValue()) {
            List<EmailConfigDO> otherEmailConfigDOS = emailConfigMapper.queryEmailConfigByDefaultStatus(status);
            if(Collections3.isNotEmpty(otherEmailConfigDOS)){
                EmailConfigDO otherEmailConfigDO = otherEmailConfigDOS.get(0);
                if(otherEmailConfigDO.getId() != id){
                    otherEmailConfigDO.setHaveDefault(DefaultEnum.NO.getValue());
                    otherEmailConfigDO.setModifyBy(userId);
                    otherEmailConfigDO.setModifyTime(LocalDateTime.now());
                    emailConfigMapper.updateById(otherEmailConfigDO);
                }
            }
        }
        EmailConfigDO emailConfigDO = emailConfigMapper.selectById(id);
        if(emailConfigDO == null){
            throw new BusinessException("记录不存在");
        }
        emailConfigDO.setHaveDefault(status);
        emailConfigDO.setModifyBy(userId);
        emailConfigDO.setModifyTime(LocalDateTime.now());
        return emailConfigMapper.updateById(emailConfigDO) > 0;
    }

    @Override
    public Long checkName(Long id, String name) {
        EmailConfigDO emailConfigDO = emailConfigMapper.selectOne(new LambdaQueryWrapper<>(EmailConfigDO.class)
                .eq(EmailConfigDO::getId, id)
                .eq(EmailConfigDO::getName, name));
        if (null == emailConfigDO) {
            return null;
        }
        return emailConfigDO.getId();
    }

    private IEmailConfigService getBean() {
        return SpringBeanUtil.getBean(IEmailConfigService.class);
    }

}
